/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.DocumentSentAddressInfoRequest;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.CaseDocumentSendinfoConfirmVo;
import com.icinfo.cloud.provider.punish.config.dto.ConfigBusiParamDocumentInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamMainService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigBusiParamDocumentInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseRelatedAppDocumentPageQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseRelatedDocumentDelDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseRelatedDocumentSaveDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.DocumentCatalogQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseRelatedDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseRelatedDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseHandlePersonRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseRelatedDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRelateDocumentInfoDto;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.ICaseDocumentSendinfoConfirmService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 案件关联文书记录表 case_related_document_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年06月17日
 */
@Service
public class CaseRelatedDocumentRecordServiceImpl extends MyBatisServiceSupport implements ICaseRelatedDocumentRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseRelatedDocumentRecordServiceImpl.class);

    @Resource
    private CaseRelatedDocumentRecordMapper caseRelatedDocumentRecordMapper;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICasePartiesRecordService partiesRecordService;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private IConfigBusiParamMainService configBusiParamMainService;
    @Resource
    private ICaseDocumentSendinfoConfirmService caseDocumentSendinfoConfirmService;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;


    @Override
    public List<CaseRelatedAppDocumentVo> getCanRelatedDocumentListByPartyAndHandle(CaseRelatedAppDocumentPageQueryDto queryDto) {
        if (ObjectUtils.isEmpty(queryDto.getCaseId())
                && ObjectUtils.isEmpty(queryDto.getHandlePersonInfoList())
                && ObjectUtils.isEmpty(queryDto.getHandlePersonInfoList())
                && ObjectUtils.isEmpty(queryDto.getPartiesLegalInfoList())) {
            throw new BusinessException("查询参数不能为空");
        }
        CaseMainInfoVo caseMainInfo = null;
        if (ObjectUtil.isNotEmpty(queryDto.getCaseId())) {
            caseMainInfo = caseMainInfoService.getCaseMainInfo(queryDto.getCaseId());
        }
        String handlePersonIds = "";
        String partyIdentityCodes = "";
        if (ObjectUtils.isEmpty(queryDto.getCaseId())
                || ObjectUtils.isEmpty(caseMainInfo)) {
            String legalUniscid = "";
            if (ObjectUtil.isNotEmpty(queryDto.getPartiesLegalInfoList())) {
                legalUniscid = queryDto.getPartiesLegalInfoList().stream().map(e -> e.getUniscid()).collect(Collectors.joining(","));
            }
            String personCertNo = "";
            if (ObjectUtil.isNotEmpty(queryDto.getPartiesPersonInfoList())) {
                personCertNo = queryDto.getPartiesPersonInfoList().stream().map(e -> e.getCertNo()).collect(Collectors.joining(","));
            }
            if (ObjectUtil.isNotEmpty(legalUniscid) && ObjectUtil.isNotEmpty(personCertNo)) {
                partyIdentityCodes = legalUniscid + "," + personCertNo;
            } else {
                partyIdentityCodes = legalUniscid + personCertNo;
            }
            handlePersonIds = queryDto.getHandlePersonInfoList().stream().map(e -> e.getHandlePersonId()).collect(Collectors.joining(","));

        } else  {
            if (!(CaseStageEnum.CASE_REGISTER.getCode().equals(caseMainInfo.getCaseCurrentStageCode())
                    || CaseStageEnum.INVESTIGATION.getCode().equals(caseMainInfo.getCaseCurrentStageCode()))) {
                throw new BusinessException("该案件环节不可查询关联文书");
            }
            if (ObjectUtil.isEmpty(partyIdentityCodes)){
                List<CasePartiesRecordVo> casePartiesInfo = partiesRecordService.getCasePartiesInfo(queryDto.getCaseId());
                partyIdentityCodes = casePartiesInfo.stream().map(e -> e.getPartyIdentityCode()).collect(Collectors.joining(","));
                if(Constant.STRING_1.equalsIgnoreCase(queryDto.getIsMaterialSupplement())){
                    queryDto.setPersonCertType(casePartiesInfo.get(0).getPartyIdentityType());
                }
            }
            if (ObjectUtil.isEmpty(handlePersonIds)){
              List<CaseHandlePersonRecordVo> handlePersonRecordVos = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(queryDto.getCaseId());
              handlePersonIds = handlePersonRecordVos.stream().map(e -> e.getHandlePersonId()).collect(Collectors.joining(","));
          }
        }

        if (ObjectUtil.isEmpty(partyIdentityCodes)){
            throw new BusinessException("当事人证件号码信息不能为空");
        }
        queryDto.setHandlePersonIds(handlePersonIds);
        queryDto.setPartyIdentityCodes(partyIdentityCodes);
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getLength(), queryDto.getOrderBy());
        List<CaseRelatedAppDocumentVo> caseRelatedAppDocumentVos = caseRelatedDocumentRecordMapper.selectNotRelatedDocumentRecordList(queryDto);
        return caseRelatedAppDocumentVos;
    }

    @Override
    public List<DocumentCatalogInfoVo> getDocumentCatalogList(DocumentCatalogQueryDto queryDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("登录失效");
        }
        if(ObjectUtil.isEmpty(queryDto.getCaseId())){
            if (ObjectUtil.isEmpty(queryDto.getCaseReasonInfoList())){
                throw new BusinessException("立案阶段案由不能为空");
            }
        }
        String busiParamId="";
        if (ObjectUtil.isNotEmpty(queryDto.getCaseId())){
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(queryDto.getCaseId());
            busiParamId=caseMainInfo.getBusiParamId();
        }else {
            //获取领域下业务参数
            RelationWorkflowInfoRequest request = new RelationWorkflowInfoRequest();
            request.setApplyAreaCode(userInfo.getAreaCode());
            request.setApplyFieldCode(queryDto.getCaseReasonInfoList().get(0).getTerritoryCode());
            List<ConfigBusiParamMain> configBusiParamMainList = configBusiParamMainService.getConfigBusiParamMainList(request);
            busiParamId=configBusiParamMainList.get(0).getId();
        }
        queryDto.setMainHandlePersonId(userInfo.getUserId().toString());
        queryDto.setHandleOrgCode(userInfo.getOrgCode());
        ConfigBusiParamDocumentInfoQueryDto infoQueryDto = new ConfigBusiParamDocumentInfoQueryDto();
        infoQueryDto.setApplyGroup("ZTC");
        infoQueryDto.setBusiParamId(busiParamId);
        List<ConfigBusiParamDocumentInfoVo> voList = configBusiParamDocumentInfoService.getCConfigBusiParamDocumentInfoByGroupList(infoQueryDto);
        List<DocumentCatalogInfoVo> catalogInfoVoList = new ArrayList<>();
        for (ConfigBusiParamDocumentInfoVo paramDocumentInfo : voList) {
            DocumentCatalogInfoVo catalogInfoVo = new DocumentCatalogInfoVo();
            catalogInfoVo.setDocumentCatalogCode(paramDocumentInfo.getDocumentCatalogCode());
            catalogInfoVo.setDocumentCatalogName(paramDocumentInfo.getDocumentCatalogName());
            catalogInfoVo.setDocumentType("1");
            catalogInfoVoList.add(catalogInfoVo);
        }
        return catalogInfoVoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveCaseRelatedDocument(CaseRelatedDocumentSaveDto saveDto) {
        //查询案件信息
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(saveDto.getCaseId());
        if (!CaseStageEnum.CASE_REGISTER.getCode().equals(caseMainInfo.getCaseCurrentStageCode())
                && !CaseStageEnum.INVESTIGATION.getCode().equals(caseMainInfo.getCaseCurrentStageCode())) {
            throw new BusinessException("该案件环节不可关联文书");
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("登录失效");
        }
        CaseRelatedDocumentRecord record = new CaseRelatedDocumentRecord();
        record.setCaseId(saveDto.getCaseId());
        record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
        record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
        record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
        record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
        record.setCreateUserId(userInfo.getUserId().toString());
        record.setCreateUserName(userInfo.getRealName());
        String caseId=saveDto.getCaseId();
        for (CaseRelateDocumentInfoDto relateDocumentInfoDto : saveDto.getRelatedDocumentList()) {
            CustomCheckParamUtil.doCheck(relateDocumentInfoDto);
            CasePartiesRecord partiesRecord = casePartiesRecordService.getCasePartiesRecordByIdentityCode(saveDto.getCaseId(),relateDocumentInfoDto.getPartyIdentityCode(), relateDocumentInfoDto.getPartyType(), null);
            if (ObjectUtils.isEmpty(partiesRecord)) {
                throw new BusinessException("该文书不是案件当事人的文书");
            }
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relateDocumentInfoDto.getDocumentCatalogCode());
            //送达地址确认书
            if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())){
                String identityCode=partiesRecord.getPartyIdentityCode();
                String identityType=partiesRecord.getPartyIdentityType();
                CaseDocumentSendinfoConfirmVo caseDocumentSendinfoConfirmVo = caseDocumentSendinfoConfirmService.getDocumentSendInfoConfirmInfoByIdentityCode( identityType,identityCode);
                if (ObjectUtil.isEmpty(caseDocumentSendinfoConfirmVo)){
                  throw new BusinessException("送达地址确认书信息不存在");
                }else {
                    CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm=new CaseDocumentSendinfoConfirm();
                    caseDocumentSendinfoConfirm.setId(caseDocumentSendinfoConfirmVo.getId());
                    caseDocumentSendinfoConfirm.setCaseId(partiesRecord.getCaseId());
                    caseDocumentSendinfoConfirm.setPartyId(partiesRecord.getPartyId());
                    caseDocumentSendinfoConfirmMapper.updateByPrimaryKeySelective(caseDocumentSendinfoConfirm);
                }
//                AppCaseBeforeDocumentRecordVo appCaseBeforeDocumentRecordVo = caseRelatedDocumentRecordMapper.selectAppCaseBeforeDocumentRecordVoById(relateDocumentInfoDto.getDocumentId());
//                CaseDocumentRecord caseDocumentRecord=new CaseDocumentRecord();
//                caseDocumentRecord.setId(BaseUtil.createUid());
//                BeanUtils.copyProperties(appCaseBeforeDocumentRecordVo,caseDocumentRecord);
//                caseDocumentRecord.setCaseId(caseId);
//                caseDocumentRecordMapper.insertSelective(caseDocumentRecord);

            }
            record.setCreateTime(LocalDateTime.now());
            record.setId(BaseUtil.createUid());
            record.setDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode());
            record.setDocumentKindName(configBusiParamDocumentInfo.getDocumentKindName());
            record.setDocumentType(relateDocumentInfoDto.getDocumentType());
            record.setDocumentId(relateDocumentInfoDto.getDocumentId());
            record.setPartyId(partiesRecord.getPartyId());
            caseRelatedDocumentRecordMapper.insertSelective(record);
        }
        return 1;
    }

    /**
     * 描述：获取通过"关联文书"渠道的案件关联文书信息
     *
     * @param caseId 案件id
     * @return List<CaseStageLinkRelateDocumentVo> 转换后的案件阶段关联文书信息
     * @author xiangyuyu
     * @date 2022-06-29 20:43
     */
    @Override
    public List<CaseStageLinkRelateDocumentVo> getRelatedDocInfoToCaseStageLinkRelateDocument(String caseId) {
        List<CaseStageLinkRelateDocumentVo> list = caseRelatedDocumentRecordMapper.selectRelatedDocInfoToCaseStageLinkRelateDocument(caseId);
        // FIXME: 2022/6/29 可能还存在需要个性化处理的字段
        return list;
    }

    @Override
    public int deleteCaseRelatedDocumentByCaseId(String caseId) {
        DocumentSentAddressInfoRequest request = new DocumentSentAddressInfoRequest();
        request.setCaseId(caseId);
        //更新关联的送达地址确认书
        List<CaseDocumentSendinfoConfirmVo> confirmInfoList = caseDocumentSendinfoConfirmService.getCaseDocumentSendInfoConfirmInfoList(caseId);
        if (ObjectUtil.isNotEmpty(confirmInfoList) && confirmInfoList.size()>0){
            for (CaseDocumentSendinfoConfirmVo confirmVo:confirmInfoList){
                CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm=new CaseDocumentSendinfoConfirm();
                caseDocumentSendinfoConfirm.setId(confirmVo.getId());
                caseDocumentSendinfoConfirm.setCaseId("");
                caseDocumentSendinfoConfirm.setPartyId("");
                caseDocumentSendinfoConfirmMapper.updateByPrimaryKeySelective(caseDocumentSendinfoConfirm);
            }
        }
        Example example=new Example(CaseRelatedDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId",caseId);
        return caseRelatedDocumentRecordMapper.deleteByExample(example);
    }

    @Override
    public int delCaseRelatedDocument(CaseRelatedDocumentDelDto delDto) {
        Example example = new Example(CaseRelatedDocumentRecord.class);
        example.createCriteria().andEqualTo("documentId",delDto.getDocumentId())
                .andEqualTo("caseId",delDto.getCaseId());
        List<CaseRelatedDocumentRecord> recordList = caseRelatedDocumentRecordMapper.selectByExample(example);
        // 更新关联的送达地址确认书
        if (recordList.get(0).getDocumentKindCode().equals("SDDZQRS")){
            Example example1 = new Example(CaseDocumentSendinfoConfirm.class);
            example1.createCriteria().andEqualTo("partyId",recordList.get(0).getPartyId())
                    .andEqualTo("caseId",delDto.getCaseId());
            CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
            caseDocumentSendinfoConfirm.setCaseId("");
            caseDocumentSendinfoConfirm.setPartyId("");
            caseDocumentSendinfoConfirmMapper.updateByExample(caseDocumentSendinfoConfirm,example1);
        }
        return caseRelatedDocumentRecordMapper.deleteByExample(example);
    }

    @Override
    public List<CaseRelateDocumentInfoDto> getCaseRelateDocumentInfoDto(String caseId, String documentKindCode, String caseStageCode) {
        return caseRelatedDocumentRecordMapper.selectCaseRelateDocumentInfoDto(caseId,documentKindCode,caseStageCode);
    }

    @Override
    public int delFastCaseRelatedDocument(String caseId, String relatedType, String documentKindCode, String documentId) {
        Example example = new Example(CaseRelatedDocumentRecord.class);

        if (ObjectUtil.isNotEmpty(documentId)){
            example.createCriteria()
                    .andEqualTo("documentKindCode",documentKindCode)
                    .andEqualTo("caseId",caseId)
                    .andEqualTo("documentId",documentId);
        }else{
            example.createCriteria().andEqualTo("relatedType",Constant.STRING_1)
                    .andEqualTo("documentKindCode",documentKindCode)
                    .andEqualTo("caseId",caseId);
        }
        List<CaseRelatedDocumentRecord> recordList = caseRelatedDocumentRecordMapper.selectByExample(example);
        // 更新关联的送达地址确认书
        if (ObjectUtil.isNotEmpty(recordList) && recordList.size()>0){
            if (recordList.get(0).getDocumentKindCode().equals("SDDZQRS")){
                Example example1 = new Example(CaseDocumentSendinfoConfirm.class);
                example1.createCriteria().andEqualTo("partyId",recordList.get(0).getPartyId())
                        .andEqualTo("caseId",caseId);
                CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
                caseDocumentSendinfoConfirm.setCaseId("");
                caseDocumentSendinfoConfirm.setPartyId("");
                caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm,example1);
            }
        }
        return caseRelatedDocumentRecordMapper.deleteByExample(example);
    }
}
